import 'package:dio/dio.dart';

import 'api_path.dart';
import 'api_result.dart';

enum Env { dev, prod }

///网络请求工具
class NetworkUtil {
  static final Dio _dio = Dio();
  static String? _baseUrl;
  static const String _dev = "https://mock.apifox.cn/m1/3051702-0-default";
  static const String _prod = "http://124.222.39.14:8001";
  static String? _token;
  static String? _refreshToken;

  //初始化方法
  static init({Env? env}) {
    _baseUrl = env == Env.prod ? _prod : _dev;
    _dio.options.baseUrl = _baseUrl!;
  }

  //设置dio
  static setDioOption({String? token, String? refreshToken}) {
      _token = token;
      _refreshToken = refreshToken;
      _dio.options = BaseOptions(headers: {"Authorization": token},baseUrl: _baseUrl!);
  }

  //get请求
  static Future<ApiResult> get({required String path,Map<String,dynamic>? queryParameters})async{
    if(_baseUrl==null){
      return ApiResult(code: -1,msg: "请先调用init初始化方法");
    }else{
      try{
        final resp = await _dio.get(path,queryParameters: queryParameters);
        if(resp.statusCode==200){
          return ApiResult.fromJson(resp.data);
        }else{
          return ApiResult(code: resp.statusCode,msg: "${resp.data}");
        }
      }catch(e){
        return ApiResult(code: -2,msg: "$e");
      }
    }
  }

  //post请求
  static Future<ApiResult> post({required String path,Map<String,dynamic>? data})async{
    if(_baseUrl==null){
      return ApiResult(code: -1,msg: "请先调用init初始化方法");
    }else{
      try{
        final resp = await _dio.post(path,data: data);
        if(resp.statusCode==200){
          return ApiResult.fromJson(resp.data);
        }else{
          return ApiResult(code: resp.statusCode,msg: "${resp.data}");
        }
      }catch(e){
        return ApiResult(code: -2,msg: "$e");
      }
    }
  }

  //刷新token
  // static Future<bool> refreshToken()async{
  //   final result = await post(path: ApiPath.refreshTokenPath,data: {
  //     "refreshToken":_refreshToken
  //   });
  //   if(result.success){
  //     _token = result.data['token'];
  //     _dio.options.headers['Authorization'] = _token;
  //     _refreshToken = result.data['refreshToken'];
  //   }
  //   return result.success;
  // }
}
